package com.wandian.audio.mvvm.audiolocal;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.utils.ActivityUtil;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.wandian.audio.R;
import com.wandian.audio.adapter.AudioLocalRecycleAdapter;
import com.wandian.audio.bean.MusicBean;
import com.wandian.audio.bean.Song;
import com.wandian.audio.databinding.AudioActivityLocalBinding;
import com.wandian.audio.db.MyDbFunctions;
import com.wandian.audio.tools.MusicCollector;
import com.wandian.audio.tools.PictureDealHelper;
import com.wandian.audio.tools.SongsCollector;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @date 2019/12/18-14:28
 * @description 本地音乐
 **/
@Route(path = RouterConfig.ROUTER_ACTIVITY_AUDIO_LOCAL)
public class AudioLocalActivity extends BaseMVVMActivity<AudioLocalActivityViewModel> {
    private AudioActivityLocalBinding dataBinding;
    private AudioLocalRecycleAdapter audioLocalRecycleAdapter;
    private MyDbFunctions myDbFunctions;
    private final int REQ_READ_EXTERNAL_STORAGE = 1;//权限请求码,1代表读取外部存储权限,2代表写存储
    @Override
    public void init(Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.audio_activity_local);
        dataBinding.setLifecycleOwner(this);
        dataBinding.setViewModel(mViewModel);
        initRecycle();
        initViewData();
        initClink();
        /*获取歌曲数据*/
        load_Songs_data();
    }

    private void initRecycle(){
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        dataBinding.recycler.setLayoutManager(layoutManager);
        audioLocalRecycleAdapter  = new AudioLocalRecycleAdapter(R.layout.audio_item_local_list_view);
        dataBinding.recycler.setAdapter(audioLocalRecycleAdapter);
        audioLocalRecycleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                Song song = (Song) baseQuickAdapter.getData().get(i);
                if(!UIUtils.isEmpty(song)){
                    Bundle bundle = new Bundle();
                    bundle.putString("music_type","local");
                    bundle.putString("music_id",song.getDataPath());
                    ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_AUDIO_MAIN).with(bundle).navigation();
                }
            }
        });
    }

    private void initViewData(){
        ActivityUtil.getInstance().showStatusView(this,dataBinding.viewSysTop,true);
        dataBinding.bindTransparentToolBar.toolBarTvTitle.setText("本地音乐");

    }

    private void initClink(){
        dataBinding.bindTransparentToolBar.toolBarIvBack.setOnClickListener(v -> {
            finish();
        });
    }

    /*---------------------存储权限以及歌曲数据---------------------*/
    /*加载歌曲数据*/
    private void load_Songs_data() {
        if (SongsCollector.size() == 0) {
            myDbFunctions = MyDbFunctions.getInstance(this);//获取数据库操作类实例
            if (!myDbFunctions.isSONGS_Null()) {
                //数据库里面有数据,直接加载数据库里面的
                new GetDB_DataTask(AudioLocalActivity.this).execute();
                return;
            }
            /*判断是否需要请求权限,然后获取歌曲数据*/
            requestPermissionByHand();
        }else {
            initSongListData();
        }
    }
    /*向用户请求权限*/
    private void requestPermissionByHand() {
        //判断当前系统的版本
        if (Build.VERSION.SDK_INT >= 23) {//6.0以上
            int checkReadStoragePermission = ContextCompat.checkSelfPermission(
                    AudioLocalActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
            //如果读取没有被授予
            if (checkReadStoragePermission != PackageManager.PERMISSION_GRANTED) {
                //请求权限,此处可以同时申请多个权限
                ActivityCompat.requestPermissions(
                        AudioLocalActivity.this, new String[]{
                                Manifest.permission.READ_EXTERNAL_STORAGE
                        }, REQ_READ_EXTERNAL_STORAGE);
            } else {//已有权限,加载歌曲
                new ScanMusicTask(AudioLocalActivity.this).execute();
            }
        }
        else{
            new ScanMusicTask(AudioLocalActivity.this).execute();
        }
    }

    /*向用户请求权限后的回调*/
    @Override
    public void onRequestPermissionsResult(int requestCode, final String[] permissions, int[] grantResults) {
        if (requestCode == REQ_READ_EXTERNAL_STORAGE) {
            // 如果请求被取消了，那么结果数组就是空的
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予了
                if (SongsCollector.size() == 0) {
                    new ScanMusicTask(AudioLocalActivity.this).execute();
//                    scanMusic();//加载歌曲数据
                }
            } else {
                Toast.makeText(AudioLocalActivity.this, "读存储权限申请失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /*扫描歌曲文件*/
    /*
     * Params：开始异步任务执行时传入的参数类型；
     * Progress：异步任务执行过程中，返回下载进度值的类型；
     * Result：异步任务执行完成后，返回的结果类型
     * 静态内部类+弱引用防止内存泄漏
     * */
    private static class GetDB_DataTask extends AsyncTask<Void, Void, Boolean> {
        private final WeakReference<AudioLocalActivity> audioLocalActivityWeakReference;

        GetDB_DataTask(AudioLocalActivity AudioLocalActivity) {
            audioLocalActivityWeakReference = new WeakReference<>(AudioLocalActivity);
        }

        //在后台任务开始执行之间调用，在主线程执行
        @Override
        protected void onPreExecute() {
            AudioLocalActivity AudioLocalActivity = audioLocalActivityWeakReference.get();
//            Toast.makeText(AudioLocalActivity,"开始加载歌曲数据",Toast.LENGTH_SHORT).show();
            //   AVLoadingIndicatorView loading_animation = AudioLocalActivity.findViewById(R.id.loading_animation);
            //  loading_animation.setVisibility(View.VISIBLE);//显示加载动画
        }

        //在子线程中运行，处理耗时任务
        @Override
        protected Boolean doInBackground(Void... params) {
            AudioLocalActivity AudioLocalActivity = audioLocalActivityWeakReference.get();
            if (AudioLocalActivity != null) {
                if (AudioLocalActivity.myDbFunctions != null) {
                    if (!AudioLocalActivity.myDbFunctions.isSONGS_Null()) {
                        //数据库里面有数据,直接加载数据库里面的
                        SongsCollector.setSongsList(AudioLocalActivity.myDbFunctions.loadAllSongs());
                        SongsCollector.song_total_number = SongsCollector.size();
                        return true;
                    }
                }
            }
            return false;
        }

        //在这个方法中可以对UI进行操作，在主线程中进行
//        @Override
//        protected void onProgressUpdate(Void... values) {
//        }

        //返回的数据会作为参数传递到此方法中，可以利用返回的数据来进行一些UI操作，在主线程中进行
        @Override
        protected void onPostExecute(Boolean result) {
            AudioLocalActivity audioLocalActivity = audioLocalActivityWeakReference.get();
            if (result){
                audioLocalActivity.initSongListData();
            } else {
                ToastUtil.show("加载歌曲数据失败");
            }
        }

    }
    //扫描加载音乐
    private static class ScanMusicTask extends AsyncTask<Void, Void, Boolean> {
        private final WeakReference<AudioLocalActivity> audioLocalActivityWeakReference ;
        ScanMusicTask(AudioLocalActivity AudioLocalActivity){
            audioLocalActivityWeakReference = new WeakReference<>(AudioLocalActivity);
        }

        @Override
        protected void onPreExecute() {
            AudioLocalActivity AudioLocalActivity = audioLocalActivityWeakReference.get();
//            Toast.makeText(AudioLocalActivity,"开始扫描本地歌曲",Toast.LENGTH_SHORT).show();
//            AVLoadingIndicatorView loading_animation = AudioLocalActivity.findViewById(R.id.loading_animation);
//            loading_animation.setVisibility(View.VISIBLE);//加载动画显示
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            AudioLocalActivity audioLocalActivity = audioLocalActivityWeakReference.get();
            ContentResolver contentResolver = audioLocalActivity.getContentResolver();
            try (Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    null, null, null, null)) {
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        //是否是音频
                        int isMusic = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));
                        //时长
                        long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
                        //是音乐并且时长大于2分钟
                        if (isMusic != 0 && duration >= 2 * 60 * 1000) {
                            //文件路径
                            String dataPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                            if (SongsCollector.isContainSong(dataPath)) {//数据库中已经有这首歌曲了,所以跳过
                                continue;
                            }
                            //歌名
                            String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                            //歌手
                            String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                            //专辑id
//                            long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                            //歌名，歌手，时长,文件路径,是否喜爱,专辑,专辑图片,是否使用默认专辑图片
                            Song song = new Song(title, artist, duration, dataPath, false, PictureDealHelper.getAlbumPicture(dataPath,96,96),
                                    false
                            );//R.drawable.song_item_picture是歌曲列表每一项前面那个图标
                            if(!SongsCollector.isContainSong(song.getDataPath())){//只添加当前列表中没有
                                SongsCollector.addSong(song);
                                if(song.getAlbum_icon() == null){
                                    song.setFlagDefaultAlbumIcon(true);
                                }
                                audioLocalActivityWeakReference.get().myDbFunctions.saveSong(song);
                            }//只添加当前列表中没有
                        }//是音乐并且时长大于2分钟
                    }//游标的移动
                }//游标不为空
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }

        //返回的数据会作为参数传递到此方法中，可以利用返回的数据来进行一些UI操作，在主线程中进行
        @Override
        protected void onPostExecute(Boolean result) {
            AudioLocalActivity audioLocalActivity = audioLocalActivityWeakReference.get();
            if(result){
                Toast.makeText(audioLocalActivity,"歌曲扫描完毕",Toast.LENGTH_SHORT).show();
                //给一些歌曲添加默认专辑图片
//                int size = SongsCollector.size();//调试用
//                Log.w("歌曲数量有","size = "+size);
                for(int i = 0; i < SongsCollector.size(); i ++){
                    Song s = SongsCollector.getSong(i);
                    if(s.getAlbum_icon() == null){
                        Bitmap b = PictureDealHelper.getAlbumPicture(audioLocalActivity, s.getDataPath(),96,96);
                        s.setAlbum_icon(b);
                    }
                }

                /*初始化歌曲列表控件,必须在获取数据后面*/
                audioLocalActivity.initSongListData();
                if (SongsCollector.size() == 0) {
                    Toast.makeText(audioLocalActivity, "本机无歌曲,请下载！", Toast.LENGTH_SHORT).show();
                }
            }else{
                Toast.makeText(audioLocalActivity,"默认专辑图片出错",Toast.LENGTH_SHORT).show();
            }
        }
    }

    /*----------------------------初始化歌曲列表-------------*/
    private void initSongListData(){
        List<MusicBean> listMusic = new ArrayList<>();
        for(Song song :SongsCollector.getSongsList()){
            MusicBean musicBean = new MusicBean();
            musicBean.setId(song.getDataPath());
            musicBean.setUrl(song.getDataPath());
            musicBean.setCommentCount("0");
            musicBean.setName(song.getTitle());
            musicBean.setNickname(song.getArtist());
            musicBean.setThumb("");
            listMusic.add(musicBean);
        }
        if(listMusic.size()>0)MusicCollector.setSongsList(listMusic);
        audioLocalRecycleAdapter.setNewData(SongsCollector.getSongsList());
    }

}
